package com.main.accountpermissionsmanagement.interfaces.facade;

import cn.dev33.satoken.secure.SaSecureUtil;
import com.main.accountpermissionsmanagement.application.service.AccountService;
import com.main.accountpermissionsmanagement.domain.account.entity.Account;
import com.main.accountpermissionsmanagement.interfaces.dto.LoginDTO;
import com.main.common.base.resp.RespBody;
import com.main.common.utils.ConfigUtil;
import com.main.common.utils.SaTokenUtil;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.validation.constraints.NotBlank;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
import java.util.List;

import static cn.dev33.satoken.sign.SaSignTemplate.key;

@Tag(name = "Account", description = "账户接口")
@RestController
@RequestMapping("")
public class AccountFacade {
    private final SaTokenUtil saTokenUtil = new SaTokenUtil();

    @Resource
    private AccountService accountService;

    @PostMapping("/test")
    public RespBody<String> test(@RequestBody @NotBlank String id) {
        saTokenUtil.Login(id,"pc");
        return RespBody.ok("登录成功");
    }
    public static RSAPrivateKey loadPrivateKey(String privateKeyPEM) throws Exception {
        // 清理 PEM 格式
        String cleanedPEM = privateKeyPEM
                .replace("-----BEGIN PRIVATE KEY-----", "")
                .replace("-----END PRIVATE KEY-----", "")
                .replaceAll("\\s+", "");

        // Base64 解码
        byte[] privateKeyBytes = Base64.getDecoder().decode(cleanedPEM);

        // 生成私钥
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKeyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        return (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
    }

    public static RSAPublicKey loadPublicKey(String publicKeyPEM) throws Exception {
        // 清理 PEM 格式
        String cleanedPEM = publicKeyPEM
                .replace("-----BEGIN PUBLIC KEY-----", "")
                .replace("-----END PUBLIC KEY-----", "")
                .replaceAll("\\s+", "");

        // Base64 解码
        byte[] publicKeyBytes = Base64.getDecoder().decode(cleanedPEM);

        // 生成公钥
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKeyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        return (RSAPublicKey) keyFactory.generatePublic(keySpec);
    }

    @PostMapping("/login")
    public RespBody<List<Account>> login(@Validated @RequestBody LoginDTO loginDTO) throws Exception {
        RSAPrivateKey privateKey = loadPrivateKey(ConfigUtil.getProperty("Default.Encrypt.private"));
        RSAPublicKey publicKey = loadPublicKey(ConfigUtil.getProperty("Default.Encrypt.public"));
        try {
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            byte[] cipherText = cipher.doFinal(Base64.getDecoder().decode(loginDTO.getPassword().replaceAll("JIAHAO","+").getBytes()));
            String decrypted = new String(cipherText);
            loginDTO.setPassword(decrypted);
            return accountService.login(loginDTO);
        } catch (Exception e) {
            e.printStackTrace();
            return RespBody.fail(e.getMessage());
        }
    }
}